package com.example.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.InMemoryAuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.lang.reflect.Array;
import java.util.Arrays;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter
{
    //密码模式需要的认证管理
    @Autowired
    AuthenticationManager authenticationManager;

    //redis存储access_token
    @Autowired
    RedisConnectionFactory redisConnectionFactory;

    @Autowired
    DataSource dataSource;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    JwtAccessTokenConverter jwtAccessTokenConverter;

    @Autowired
    CustomAdditionalInformation customAdditionalInformation;

    @Bean
    TokenStore tokenStore()
    {
        //return new RedisTokenStore(redisConnectionFactory);
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    JwtAccessTokenConverter jwtAccessTokenConverter()
    {
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        converter.setSigningKey("admin");
        return converter;
    }

    @Bean
    ClientDetailsService clientDetailsService()
    {
        return new JdbcClientDetailsService(dataSource);
    }

    @Bean
    public PasswordEncoder passwordEncoder()
    {
        return new BCryptPasswordEncoder();
    }

    //主要用来配置 Token 的一些基本信息，例如 Token 是否支持刷新、Token 的存储位置、
    // Token 的有效期以及刷新 Token 的有效期等等。
    @Bean
    AuthorizationServerTokenServices tokenServices()
    {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setClientDetailsService(clientDetailsService());
        tokenServices.setSupportRefreshToken(true);//是否支持刷新
        tokenServices.setTokenStore(tokenStore());
        //tokenServices.setAccessTokenValiditySeconds(60);//token有效期
        //tokenServices.setRefreshTokenValiditySeconds(60 * 60 * 24 * 7);//token刷新机制保留的时间
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers(Arrays.asList(jwtAccessTokenConverter,customAdditionalInformation));
        tokenServices.setTokenEnhancer(tokenEnhancerChain);
        return tokenServices;
    }

    //配置安全规则
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception
    {
        security.checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    }

    //校验客户端信息
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception
    {
        clients.withClientDetails(clientDetailsService());

//        clients.inMemory()
//                .withClient("admin")
//                .secret(new BCryptPasswordEncoder().encode("123"))
//                .resourceIds("res1")
////                .authorizedGrantTypes("authorization_code", "refresh_token","implicit")
//                .authorizedGrantTypes("authorization_code", "refresh_token", "password")
//                .scopes("all")
//                //自动通过授权,类似于静默授权！
//                .autoApprove(true)
////                .redirectUris("http://localhost:8082/index.html");
////                .redirectUris("http://localhost:8082/01.html");
//                .redirectUris("http://localhost:8082/02.html");
    }

    //这里用来配置令牌的访问端点和令牌服务
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception
    {
        endpoints.authorizationCodeServices(authorizationCodeServices())
                //由于使用了 password 模式之后，用户要进行登录，
                // 所以我们需要配置一个 AuthenticationManager
                .authenticationManager(authenticationManager)
                .tokenServices(tokenServices());
    }

    //授权码code放在内存中
    @Bean
    AuthorizationCodeServices authorizationCodeServices()
    {
        return new InMemoryAuthorizationCodeServices();
    }
}
